package dkbta.processing.data;

import java.util.List;

import dkbta.ontology.elements.Element;
import dkbta.ontology.elements.ElementDef;

/**
 * A compound object holding a reference to the element to be sent, its instances, the
 * associated patient's id and where to send the instances
 * 
 * @author Uri Kanonov
 */
public class DataBatch{
	/** The associated element's definition */
	public final ElementDef elementDef;

	/** The instances to be sent */
	public final List<? extends Element> elements;

	/** The associated patient's id */
	public final int patientId;

	/** Information on where to send the instances to */
	public final SendTo sendTo;

	/**
	 * Initializes a data batch
	 * 
	 * @param elementDef The associated element's definition
	 * @param sendTo Information on where to send the instances to
	 * @param elements The instances to be sent
	 * @param patientId The associated patient's id
	 */
	public DataBatch(ElementDef elementDef, SendTo sendTo,
		List<? extends Element> elements, int patientId){
		this.elementDef = elementDef;
		this.sendTo = sendTo;
		this.elements = elements;
		this.patientId = patientId;
	}

	@Override
	public String toString(){
		return "<Pid " + patientId + ", " + elementDef.getElementType() + " - "
				+ elementDef.getName() + ">";
	}

	/**
	 * Serializes the elements in the batch with start times in milliseconds.<br>
	 * <br>
	 * If there is at least one instance then the format is ([Value] means the value is
	 * optional, depending on the element type):
	 * 
	 * <pre>
	 * #OfInstances
	 * Pid,ElementType,ElementName,StartTime,EndTime,[Value] (first instance)
	 * ...
	 * Pid,ElementType,ElementName,StartTime,EndTime,[Value] (last instance)
	 * </pre>
	 * 
	 * Otherwise (if the number of instances is zero) the format is:
	 * 
	 * <pre>
	 * #OfInstances
	 * Pid,ElementType,ElementName
	 * </pre>
	 * 
	 * @return The serialized content.
	 */
	public String serialize(){
		int numOfInstances = elements.size();
		if (numOfInstances == 0){
			return numOfInstances + "\n" + patientId + "," + elementDef.getElementType()
					+ "," + elementDef.getName() + "\n";
		}else{
			StringBuilder sb = new StringBuilder(String.valueOf(numOfInstances))
					.append("\n");
			for (Element e : elements){
				e.serializeMillis(patientId, sb).append("\n");
			}
			return sb.toString();
		}
	}
}
